package com.example.demo.service.serviceImpl;
//import cn.hutool.http.HttpUtil;
//import cn.hutool.json.JSONObject;
//import cn.hutool.json.JSONUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.entity.*;
import com.example.demo.mapper.ActivityMapper;
import com.example.demo.mapper.AwardMapper;
import com.example.demo.mapper.GoodsMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.tencentcloudapi.mps.v20190612.models.UserDefineAsrTextReviewTemplateInfo;
import org.intellij.lang.annotations.RegExp;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    //https://api.weixin.qq.com/sns/jscode2session
    @Value("${wx.online_people_url}")
    private String ONLINE_PEOPLE_URL;

    //小程序的AppID
    @Value("${wx.appId}")
    private String APP_ID;

    //小程序的AppSecret
    @Value("${wx.appSecret}")
    private String SECRET;

    @Resource
    private UserMapper userMapper;
    @Override
    public User wxLogin(User user){
        JSONObject jsonObject = JSONUtil.parseObj(getMsgByWx(user.getCode()));
        String ifSuccess = jsonObject.getStr("isSuccess");
        if(ifSuccess != null){
            String openId = jsonObject.getStr("openid");
            User newUser = new User();
            newUser.setOpenId(openId);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("open_id",openId);
            List<User> res = userMapper.selectList(queryWrapper);
            if(res.isEmpty()) {
                userMapper.insert(newUser);
            }
            return newUser;
        }else{
            return null;
        }
    }
    public String getMsgByWx(String code){
        String baseUrl = ONLINE_PEOPLE_URL + "?appid=" + APP_ID + "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        String result = HttpUtil.get(baseUrl);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(!jsonObject.isNull("session_key")) {
            //成功获取到session_key等数据
            return result.substring(0,result.length()-1)+",\"isSuccess\":\"true\"}";
        }else {
            //失败，没获取到session_key等数据
            return "{\"session_key\":\"\",\"openid\":\"\",\"isSuccess\":\"false\"}";
        }
    }

    @Override
    public User selectUserById(String openId){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("open_id",openId);
        List<User> res=userMapper.selectList(queryWrapper);
        if(res!=null&&!res.isEmpty()){
            return res.get(0);
        }else{
            return null;
        }
    }

    @Override
    public long getUserCunt(){
        IPage<User> page=new Page<>();
        userMapper.selectPage(page,null);
        return page.getTotal();
    }

    @Resource
    private AwardMapper awardMapper;

    @Resource
    private ActivityMapper activityMapper;
    public List<Activity> getUserActivity(String openId){
        QueryWrapper<UserAward> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id",openId);
        List<UserAward> list = awardMapper.selectList(queryWrapper);
        List<Activity> activityList = new ArrayList<>();
        for(UserAward res : list){
            QueryWrapper<Activity> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("activity_id",res.getActivityId());
            activityList.add(activityMapper.selectOne(queryWrapper1));
        }
        return activityList;
    }

    @Resource
    private GoodsMapper goodsMapper;
    public AwardMessage getAwardMessage(String orderId){
        QueryWrapper<UserAward> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        UserAward award = awardMapper.selectOne(queryWrapper);

        Goods goods = goodsMapper.selectById(award.getGoodId());

        Activity activity = activityMapper.selectById(award.getActivityId());
        String activityName = activity.getActivityName();

        AwardMessage awardMessage = new AwardMessage(goods,award.getActivityId(),activityName,award.getOrderDate(),award.getShipStatus());
        return awardMessage;
    }

    public int confirmRecipt(String orderId){
        UpdateWrapper<UserAward> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("order_id",orderId).set("ship_status",2);
        int res=awardMapper.update(null,updateWrapper);
        return res;
    }


}
